package com.yuanqi.Service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanqi.Common.config.ThreadLocalConfig;
import com.yuanqi.Mapper.CommentMapper;
import com.yuanqi.Mapper.UserMapper;
import com.yuanqi.Common.Pojo.Vo.commentVo;
import com.yuanqi.Common.Pojo.entity.Comment;
import com.yuanqi.Common.Pojo.entity.User;
import com.yuanqi.Service.CommentService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Resource
    CommentMapper commentMapper;
    @Resource
    ThreadLocalConfig threadLocalConfig;
    @Resource
    UserMapper userMapper;

    /*
    获取评论，先得到树结构，然后吧树结构的chidren变成和父亲同级就可以了，前端就用fid来判断就行
    * */
    @Override
    public List<commentVo> getCommentByPostId(Integer postId, Integer current,Integer size) {
        Page<Comment> page = new Page<>(current, size);
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getPostId, postId);
        wrapper.eq(Comment::getFid, 0);
        wrapper.orderByDesc(Comment::getCreateTime);
        Page<Comment> page1 = commentMapper.selectPage(page, wrapper);
        List<Comment> list1 = page1.getRecords();
        List<Comment> comments = new ArrayList<>();
        comments.addAll(list1);
        getChidrencomment(list1, comments);

        List<Tree<Integer>> treeList = TreeUtil.build(comments, 0, (name, tree) -> {
            tree.setParentId(name.getFid());
            tree.setId(name.getId());
            tree.putAll(BeanUtil.beanToMap(name));

        });
        String jsonStr = JSONUtil.toJsonStr(treeList);
        JSONArray jsonArray = JSONUtil.parseArray(jsonStr);
        List<Comment> list = new ArrayList<>();
        // 遍历 JSONArray 并转换为 Comment 对象
        for (int i = 0; i < jsonArray.size(); i++) {
            Comment comment = jsonArray.getBean(i, Comment.class);
            list.add(comment);
        }
        list.sort((t1, t2) -> {
            return t2.getCreateTime().compareTo(t1.getCreateTime());
        });

        List<commentVo> list2 = new ArrayList<>();
        getlist(list, list2);
        return list2;
    }

    @Override
    public Comment AddComment(commentVo commentVo) {
        if (commentVo.getFid() != 0) {
            commentMapper.updateByCommentId(commentVo.getFid());
        }
        Comment bean = BeanUtil.toBean(commentVo, Comment.class);
        bean.setCreateTime(System.currentTimeMillis()/1000);
        Long userId = Long.valueOf(threadLocalConfig.get().get("userId").toString());
//        Long userId = 400L;
        bean.setUserId(userId);
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, userId));
        bean.setUserPic(user.getUserpic());
        bean.setNikeName(user.getNikeName());
        commentMapper.insert(bean);
        return  bean;
    }

    private void getChidrencomment(List<Comment> list, List<Comment> comments) {
        for (Comment item : list) {
            if (item.getFnum() != 0) {
                List<Comment> list1 = commentMapper.selectList(new LambdaQueryWrapper<Comment>().eq(Comment::getFid, item.getId()));
                comments.addAll(list1);
                getChidrencomment(list1, comments);
            }
        }
    }

    private void getlist(List<Comment> list, List<commentVo> list1) {
        for (Comment comment : list) {
            commentVo bean = BeanUtil.toBean(comment, commentVo.class);
            list1.add(bean);
            if (comment.getChildren() != null) {
                getlist(comment.getChildren(), list1);
            }

        }
    }

}
